package l1j.server.server.model.spawn;

import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.server.GeneralThreadPool;
import l1j.server.server.model.L1Object;
import l1j.server.server.model.L1World;
import l1j.server.server.model.Instance.L1MonsterInstance;
import l1j.server.server.model.Instance.L1NpcInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.utils.collections.Lists;

public class SpawnRefresher implements Runnable {

	private static SpawnRefresher _instance = new SpawnRefresher();

	private static Logger _log = Logger.getLogger(SpawnRefresher.class
			.getName());

	public static void initilize() {
		GeneralThreadPool.getInstance().scheduleAtFixedRate(_instance,
				5 * 60 * 1000, 5 * 60 * 1000);
	}

	public void run() {
		try {
			System.out.println("SpawnRefresher CHECK:");
			Collection<L1PcInstance> players = L1World.getInstance()
					.getAllPlayers();
			List<Integer> list = Lists.newList();
			outer: for (int mapId : SpawnTable.getInstance().getSpawnedMaps()) {
				if (mapId == 4) {
					continue;
				}
				for (L1PcInstance pc : players) {
					if (pc.getMapId() == mapId) {
						continue outer;
					}
				}
				System.out.println("Cleaning spawn mapid=" + mapId);
				list.add(mapId);
				for (L1Object obj : L1World.getInstance().getObject()) {
					if (obj instanceof L1NpcInstance
							&& !(obj instanceof L1MonsterInstance)) {
						if (obj.getMapId() == mapId) {
							((L1NpcInstance) obj).deleteMeAndNoSpawn();
						}
					}
				}
			}
			for (int mapId : list) {
				SpawnTable.getInstance().getSpawnedMaps().remove(mapId);
			}
			list.clear();
			outer: for (int mapId : NpcSpawnTable.getInstance()
					.getSpawnedMaps()) {
				if (mapId == 4) {
					continue;
				}
				for (L1PcInstance pc : players) {
					if (pc.getMapId() == mapId) {
						continue outer;
					}
				}
				System.out.println("Cleaning npcspawn mapid=" + mapId);
				list.add(mapId);
				for (L1Object obj : L1World.getInstance().getObject()) {
					if (obj instanceof L1MonsterInstance) {
						L1MonsterInstance mon = (L1MonsterInstance) obj;
						if (obj.getMapId() == mapId && !mon.isBoss()) {
							mon.deleteMeAndNoSpawn();
						}
					}
				}
			}
			for (int mapId : list) {
				NpcSpawnTable.getInstance().getSpawnedMaps().remove(mapId);
			}
			list.clear();
		} catch (Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		System.out.println("SpawnRefresher CHECK OVER");
		System.gc();
	}
}
